package com.ruoyi.framework.security.handle

import com.alibaba.fastjson2.JSON
import com.ruoyi.common.constant.Constants
import com.ruoyi.common.constant.HttpStatus
import com.ruoyi.common.utils.ServletUtils
import com.ruoyi.common.utils.StringUtils
import com.ruoyi.framework.manager.AsyncManager
import com.ruoyi.framework.manager.factory.AsyncFactory
import com.ruoyi.framework.security.service.TokenService
import com.ruoyi.framework.web.domain.AjaxResult
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.context.annotation.Configuration
import org.springframework.security.core.Authentication
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler
import java.io.IOException
import javax.servlet.ServletException
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

/**
 * 自定义退出处理类 返回成功
 *
 * @author ruoyi
 */
@Configuration
open class LogoutSuccessHandlerImpl : LogoutSuccessHandler {
    @Autowired
    private val tokenService: TokenService? = null

    /**
     * 退出处理
     *
     * @return
     */
    @Throws(IOException::class, ServletException::class)
    override fun onLogoutSuccess(
        request: HttpServletRequest,
        response: HttpServletResponse,
        authentication: Authentication?
    ) {
        tokenService!!.getLoginUser(request)?.let {
            val userName = it.username
            // 删除用户缓存记录
            tokenService.delLoginUser(it.token)
            // 记录用户退出日志
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(userName, Constants.LOGOUT, "退出成功"))
        } ?: ServletUtils.renderString(response, JSON.toJSONString(AjaxResult.error(HttpStatus.SUCCESS, "退出成功")))

    }
}
